package com.jh.fcsm.config;

import com.jh.fcsm.common.exception.ServiceException;
import com.jh.fcsm.constant.CommonConstant;
import com.jh.fcsm.constant.TokenConstants;
import com.jh.fcsm.util.security.GoogleAuthenticationTool;
import com.jh.fcsm.util.security.RSAEncrypt;
import com.jh.fcsm.util.txt.StringUtils;
import org.springframework.security.authentication.BadCredentialsException;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;

import java.util.Base64;
import java.util.regex.Pattern;

public class MyPasswordEncoder implements PasswordEncoder {

    private final BCryptPasswordEncoder bp;

    public MyPasswordEncoder() {
        bp = new BCryptPasswordEncoder();
    }

    @Override
    public String encode(CharSequence rawPassword) {
        return bp.encode(rawPassword);
    }

    @Override
    public boolean matches(CharSequence rawPassword, String encodedPassword) {

        if(StringUtils.isEmpty(encodedPassword)){
            throw new ServiceException("非法请求");
        }
        //google 用户key 当第一次登录时是没有的提示用记绑定
        String google_key = null;
        //用户数据库的密码
        String password = encodedPassword;
        //此用户是否要效验google安全认证
        boolean googleFlag = false;
        //用户已绑定的情况下，输入的验证码，验证码是在密码后输入的
        String google_code = null;

        //判断当前登录是否要验证google认证
        if(encodedPassword.contains(TokenConstants.GOOGLE_AUTHENTICATOR_FLAG)){
            password=encodedPassword.split(TokenConstants.GOOGLE_AUTHENTICATOR_FLAG)[1];
            google_key=encodedPassword.split(TokenConstants.GOOGLE_AUTHENTICATOR_FLAG)[0];
            googleFlag=true;
        }

        String raw = null;
        try {
            //前台输入的密码解密
            raw = RSAEncrypt.privateKeyDecrypt(rawPassword.toString(), TokenConstants.PRIVATE_KEY);
            if(googleFlag){
                if(!StringUtils.isEmpty(google_key)) {
                    //如果要验证google认证 提取用户输入的google验证码
                    google_code = raw.substring(raw.length() - 6);
                    raw = raw.substring(0, raw.length() - 6);
                }
            }
        } catch (Exception e) {
            throw new ServiceException("非法请求");
        }
        if(bp.matches(raw, password)){
            if (!Pattern.matches(CommonConstant.REGCH, raw)) {
                throw new BadCredentialsException("您的密码复杂度太低请修改密码后登录");
            }
            //当用户要验证google 认证时 又没绑定提示用户绑定
            if (googleFlag&&StringUtils.isEmpty(google_key)) {
                throw new BadCredentialsException("请绑定密钥");
            }
            if(googleFlag){
                //用户输入的google认证码与系统的对比
                String code=GoogleAuthenticationTool.getTOTPCode(google_key);
                return code.equals(google_code);
            }
            return true;
        }else{
            return false;
        }
    }
}
